using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FrameWork;

public class SpawnManager : MonoBehaviour
{
    [Header("生成范围")]
    [SerializeField] private Vector2 spawnAreaSetting;
    private Vector2 spawnAreaLeft;
    private Vector2 spawnAreaRight;
    // 用于存储已生成位置
    private List<Vector2> generatedPositions = new List<Vector2>();

   
    void Start()
    {
        spawnAreaLeft = new Vector2(transform.position.x - spawnAreaSetting.x, transform.position.y - spawnAreaSetting.y);
        spawnAreaRight = new Vector2(transform.position.x + spawnAreaSetting.x, transform.position.y + spawnAreaSetting.y);
        // 生成15个OreAgent和15个AppleTree
        for (int i = 0; i < 15; i++)
        {
            // 确保生成OreAgent和AppleTree
            GenerateObject("OreAgent");
            GenerateObject("AppleTree");
        }
    }

    /// <summary>
    /// 生成指定的物体
    /// </summary>
    /// <param name="objectName">物体名称</param>
    private void GenerateObject(string objectName)
    {
        // 尝试生成物体，直到找到一个有效位置
        int maxAttempts = 1000; // 防止无限循环
        Vector2 spawnPosition = Vector2.zero;

        for (int attempt = 0; attempt < maxAttempts; attempt++)
        {
            // 随机生成位置
            spawnPosition = new Vector2(
                Random.Range(spawnAreaLeft.x, spawnAreaRight.x),
                Random.Range(spawnAreaLeft.y, spawnAreaRight.y)
            );

            // 检查是否与已生成的位置重叠或间隔小于2
            bool isValidPosition = true;
            foreach (Vector2 pos in generatedPositions)
            {
                if (Vector2.Distance(spawnPosition, pos) < 2f)
                {
                    isValidPosition = false;
                    break;
                }
            }

            if (isValidPosition)
            {
                // 如果找到有效位置，跳出循环
                break;
            }
        }

        // 如果生成的位置有效
        if (spawnPosition != Vector2.zero)
        {
            // 从对象池生成物体
            GameObject obj = ObjectPool.Instance.Spawn(objectName);
            obj.transform.position = spawnPosition;
            obj.gameObject.name = objectName;
            // obj.transform.SetParent(transform);

            // 将该位置添加到已生成位置列表
            generatedPositions.Add(spawnPosition);
        }
        else
        {
            Debug.LogWarning($"无法为 {objectName} 找到有效的生成位置！");
        }
    }
}